
import { createApp } from 'vue'
import pinia from '@/store/index';
import { Page } from '@/store/page';
import App from './App.vue'
import router from './router';
import { i18n } from '@/languages';
import "@/assets/setEvent.ts"
import "@/assets/resetStyle.scss"
import '@/styles/index.scss'
import '@nutui/nutui/dist/packages/notify/style/css';
import '@nutui/nutui/dist/packages/toast/style/css';
import '@nutui/nutui/dist/packages/dialog/style/css';
import shrinkOnClick from '@/directives/shrinkOnClick';
import longPress from '@/directives/longPress';
import thumb from "@/directives/thumb"
import { IconFont } from '@nutui/icons-vue'
import '@nutui/icons-vue/dist/style_iconfont.css'
import { showToast } from '@nutui/nutui';
import imgT from '@/components/Imgt.vue'
import { currencyMoney } from '@/utils/publicMethods';
import { User } from "@/store/user"
import PKwebsocket from "@/lolo/Ws";
import { MessageMapRegister } from "@/netBase/MessageMapRegister";
import lazyPlugin from 'vue3-lazy'
import { setLanguage } from "@/languages/index"
// @ts-ignore
import pako from "pako"
// @ts-ignore
import { registerSW } from 'virtual:pwa-register';


MessageMapRegister.register();
setTimeout(() => {
    const FastClick = require("fastclick")
    // 初始化 FastClick
    if (FastClick && FastClick.FastClick && FastClick.FastClick.attach) {
        FastClick.FastClick.attach(document.body);
    }
}, 1000)
export const getLocale = async (settings: any) => { // 获取多语言配置
    let adminI18n: any = {}
    try {
        adminI18n = JSON.parse(sessionStorage.getItem('global_adminI18n') || '{}')
    } catch {
        adminI18n = {}
    }
    if (!adminI18n.zh || !adminI18n.vn || !adminI18n.en) {
        const adminI18nRes = await fetch(settings.admin_i18n_add_url + '?' + new Date().getTime())
        if (!adminI18nRes.ok) {
            return showToast.fail('admin_i18n_err')
        }
        adminI18n = await adminI18nRes.json()
    } else {
        setTimeout(() => {
            fetch(settings.admin_i18n_add_url + '?' + new Date().getTime()).then(adminI18nRes => {
                if (!adminI18nRes.ok) return
                adminI18nRes.json().then(data => {
                    setData(data)
                })
            })
        }, 3000)
    }
    setData(adminI18n)
    function setData(d: any) {
        sessionStorage.setItem('global_adminI18n', JSON.stringify(d))
        i18n.global.mergeLocaleMessage('zh-CN', d.zh)
        i18n.global.mergeLocaleMessage('vi-VN', d.vn)
        i18n.global.mergeLocaleMessage('en-US', d.en)
        Page(pinia).setAdminI18n(d)
        setLanguage()
    }
}

export const getSetting = async () => {
    const urlParams = new URLSearchParams(window.location.search);
    // 获取所有参数 
    const params:any = {};
    urlParams.forEach((value, key) => {
      params[key] = value;
    });
    console.error('参数:', params); 
    if (params.c) {
        sessionStorage.setItem('c', params.c)
    }
    // todo 暂时写死环境方便测试
    const c:any = params.c || sessionStorage.getItem('c') || 'develop'
    // const c = 'jason'
    const settingUrl = `https://config.pkbet.cloud/pkbet_${c}.json`

    return new Promise(async resolve => {
        // 53测试环境
        // const settingsRes2 = await fetch('https://yuenan-1317897257.cos.ap-singapore.myqcloud.com/yuenan/config_pk_test.json?' + new Date().getTime());
        let settings: any = {}
        try {
            settings = JSON.parse(sessionStorage.getItem('global_settings') || '{}')
        } catch {
            settings = {}
        }
        if (!settings.third_game_manage) {
            const settingsRes1 = await fetch(settingUrl + '?' + new Date().getTime())
            if (!settingsRes1.ok) {
                return showToast.fail('config_json_err')
            }
            settings = await settingsRes1.json()
        } else {
            setTimeout(() => {
                fetch(settingUrl + '?' + new Date().getTime()).then(settingsRes1 => {
                    if (!settingsRes1.ok) return
                    settingsRes1.json().then((settings: any) => {
                        settings._backend_upload = settings.backend_upload // 保留原始的 backend_upload
                        settings.backend_upload = settings.media_url // 全局替换已使用的 backend_upload 为 media_url
                        Page(pinia).setSettings(settings)
                        localStorage.setItem('chat_ws', settings.chat_res?.chat_ws)
                        sessionStorage.setItem('global_settings', JSON.stringify(settings))
                    })
                })
            }, 3000)
        }
        settings._backend_upload = settings.backend_upload // 保留原始的 backend_upload
        settings.backend_upload = settings.media_url // 全局替换已使用的 backend_upload 为 media_url
        sessionStorage.setItem('global_settings', JSON.stringify(settings))
        User(pinia).getUserLoginInfo() // 同步缓存的用户信息
        Page(pinia).setSettings(settings) // 同步获取到的全局配置
        localStorage.setItem('chat_ws', settings.chat_res?.chat_ws)
        resolve({})
        PKwebsocket.instance.init() // 初始化websocket
        getLocale(settings) // 获取多语言配置
        setTimeout(() => {
            // 获取热门数据
            if (settings.third_game_manage_hot) {
                let sessionHotHomeGameData: any = []
                try {
                    sessionHotHomeGameData = JSON.parse(sessionStorage.getItem('global_hotGameData') || '[]')
                } catch {
                    sessionHotHomeGameData = []
                }
                if (sessionHotHomeGameData && sessionHotHomeGameData.length) {
                    Page(pinia).setHomePageGameData(sessionHotHomeGameData)
                    setTimeout(() => {
                        fetch(settings.third_game_manage_hot + '?' + new Date().getTime()).then((homeGameDataRes: any) => {
                            if (!homeGameDataRes.ok) return showToast.fail('third_hotgame_manage_err')
                            homeGameDataRes.arrayBuffer().then((buffer: any) => {
                                const uint8Array = new Uint8Array(buffer);
                                const decompressedData = pako.ungzip(uint8Array, { to: 'string' });
                                console.error('热门游戏数据:', JSON.parse(decompressedData))
                                // Page(pinia).setHomePageGameData(JSON.parse(decompressedData))
                                sessionStorage.setItem('global_hotGameData', JSON.stringify(JSON.parse(decompressedData)))
                            })
                        })
                    }, 5000)
                } else {
                    Page(pinia).setHotGameIsLoading(true)
                    fetch(settings.third_game_manage_hot + '?' + new Date().getTime()).then((homeGameDataRes: any) => {
                        if (!homeGameDataRes.ok) return showToast.fail('third_hotgame_manage_err')
                        homeGameDataRes.arrayBuffer().then((buffer: any) => {
                            const uint8Array = new Uint8Array(buffer);
                            const decompressedData = pako.ungzip(uint8Array, { to: 'string' });
                            Page(pinia).setHomePageGameData(JSON.parse(decompressedData))
                            sessionStorage.setItem('global_hotGameData', JSON.stringify(JSON.parse(decompressedData)))
                        }).finally(() => {
                            Page(pinia).setHotGameIsLoading(false)
                        })
                    })
                }
            }
            // 获取三方游戏数据
            let sessionHomeGameData: any = []
            try {
                sessionHomeGameData = JSON.parse(sessionStorage.getItem('global_homeGameData') || '[]')
            } catch {
                sessionHomeGameData = []
            }
            if (sessionHomeGameData && sessionHomeGameData.length) {
                Page(pinia).setHomePageGameData(sessionHomeGameData)
                setTimeout(() => {
                    fetch(settings.third_game_manage + '?' + new Date().getTime()).then((homeGameDataRes: any) => {
                        if (!homeGameDataRes.ok) return showToast.fail('third_game_manage_err')
                        homeGameDataRes.arrayBuffer().then((buffer: any) => {
                            const uint8Array = new Uint8Array(buffer);
                            const decompressedData = pako.ungzip(uint8Array, { to: 'string' });
                            console.error('三方游戏数据:', JSON.parse(decompressedData))
                            // Page(pinia).setHomePageGameData(JSON.parse(decompressedData))
                            sessionStorage.setItem('global_homeGameData', JSON.stringify(JSON.parse(decompressedData)))
                        })
                    })
                }, 8000)
            } else {
                Page(pinia).setGameIsLoading(true)
                fetch(settings.third_game_manage + '?' + new Date().getTime()).then((homeGameDataRes: any) => {
                    if (!homeGameDataRes.ok) return showToast.fail('third_game_manage_err')
                    homeGameDataRes.arrayBuffer().then((buffer: any) => {
                        const uint8Array = new Uint8Array(buffer);
                        const decompressedData = pako.ungzip(uint8Array, { to: 'string' });
                        Page(pinia).setHomePageGameData(JSON.parse(decompressedData))
                        sessionStorage.setItem('global_homeGameData', JSON.stringify(JSON.parse(decompressedData)))
                    }).finally(() => {
                        Page(pinia).setGameIsLoading(false)
                    })
                })
            }

        }, 0)

    })
}
getSetting().then(() => {
    const app = createApp(App);
    app.component('ImgT', imgT)
    app.directive('shrink-on-click', shrinkOnClick);
    app.directive('longpress', longPress);
    app.directive('thumb', thumb);
    app.config.globalProperties.$currencyMoney = currencyMoney
    app.use(pinia).use(i18n).use(IconFont).use(router).use(lazyPlugin, {
        loading: require('@/assets/img-default.svg'), // 图片加载时默认图片
        error: require('@/assets/img-error.svg'), // 图片加载失败时默认图片
    }).mount('#app');


    // 注册 Service Worker
    // console.error(' 注册 Service Worker', registerSW)
    registerSW({
        onNeedRefresh() {
            console.log('New content is available; please refresh.');
        },
        onOfflineReady() {
            console.log('App is ready for offline use.');
        },
    });
})

